package com.landun.market.pojo.enums;

import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 数据状态类型
 * <p>
 * 0 ~ 4:无效
 * > 4:有效 或其它状态
 * </p>
 *
 * @author jiang.chuan
 * @date 2018-05-05
 */
public enum StateCode implements IEnumType {
    INACTIVE(0, "无效"),
    DISABLED(1, "禁用"),
    ACTIVE(5, "有效"),       // 默认有效状态

    ;

    private final static Map<Integer, StateCode> BY_CODE_MAP
            = Arrays.stream(StateCode.values()).collect(Collectors.toMap(StateCode::code, code -> code));

    private final static Map<String, StateCode> BY_NAME_MAP
            = Arrays.stream(StateCode.values()).collect(Collectors.toMap(code -> code.name().toLowerCase(), code -> code));


    private final int code;
    private final String desc;

    /**
     * @param code 代码
     * @param desc 描述
     */
    StateCode(final int code, final String desc) {
        this.code = code;
        this.desc = desc;
    }

    @Override
    public int code() {
        return this.code;
    }

    @Override
    public String desc() {
        return this.desc;
    }

    /**
     * @param code 代码
     * @return 转换出来的状态码
     */
    public static StateCode parse(Integer code) {
        return BY_CODE_MAP.get(code);
    }

    public static StateCode parse(Integer code, StateCode defaultState) {
        return BY_CODE_MAP.getOrDefault(code, defaultState);
    }

    /**
     * @param name 名字
     * @return 转换出来的状态码
     */
    public static StateCode parse(String name) {
        if (StringUtils.isBlank(name)) {
            return null;
        }
        return BY_NAME_MAP.get(name.trim().toLowerCase());
    }

    public static StateCode parse(String name, StateCode defaultState) {
        if (StringUtils.isBlank(name)) {
            return defaultState;
        }
        return BY_NAME_MAP.getOrDefault(name.trim().toLowerCase(), defaultState);
    }
}
